package cfdt.redis.lock;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class RedisDistributedLock {
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    
    private final Long SUCCESS = 1L;

    @Autowired
    private StringRedisTemplate redisTemplate;
    
    private String getRedisKey(String lockType, String lockKey) {
        StringBuilder redisKeyBuilder = new StringBuilder();
        redisKeyBuilder.append("DisributedLock:").append(StrUtil.trim(lockType))
            .append(":").append(StrUtil.trim(lockKey));
        return redisKeyBuilder.toString();
    }
    
    public boolean tryLock(String lockType, String lockKey, String lockValue, int expireTime) {
        try {
            String redisLockKey = getRedisKey(lockType, lockKey);
            logger.info("尝试获取锁, redisLockKey={}, lockValue={},expireTime={}", redisLockKey, lockValue, expireTime);
            boolean result = redisTemplate.opsForValue().setIfAbsent(redisLockKey, lockValue, expireTime, TimeUnit.SECONDS);
            if(result) {
                logger.info("获取锁成功");
            } else {
                logger.info("获取锁失败");
            }
            return result;
        } catch (Exception e) {
            logger.error("获取锁异常", e);
            return false;
        }

    }
    
    public boolean releaseLock(String lockType, String lockKey, String lockValue) {
        try {
            String redisLockKey = getRedisKey(lockType, lockKey);
            logger.info("释放锁, redisLockKey={}, lockValue={}", redisLockKey, lockValue);
            String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
            
            List<String> keyList = new ArrayList<>();
            keyList.add(redisLockKey);
            
            RedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
            Object executeResult = redisTemplate.execute(redisScript, keyList, lockValue);
            boolean result = SUCCESS.equals(executeResult);
            if(result) {
                logger.info("释放锁成功");
            } else {
                logger.info("释放锁失败");
            }
            return result;
        } catch (Exception e) {
            logger.error("释放锁异常", e);
            return false;
        }
    }
    
}
